package com.heima.wemedia.interceptor;

import com.heima.utils.thread.WmThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author Lijx
 * @Date 2024-07-21 16:47
 */
@Component
public class WmTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求头中的用户id
        String userId = request.getHeader("userId");

        //判断用户id是否存在
        if (!StringUtils.isEmpty(userId)) {
            //将用户id存入threadLocal中
            WmThreadLocalUtil.setUserId(Integer.valueOf(userId));
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理threadLocal中用户id，释放内存
        WmThreadLocalUtil.remove();
    }
}
